import processing.net.*; 
import processing.core.*;

class Mobile2Socket {
  
  //config variables  
  private int port    = 8484;
  private String host = "127.0.0.1";
  private boolean DEBUG = true;
  
  //helpers variables
  private String dataIn;
  private String clientAddress;
  private String clientCommand;
  
  //
  private Client socketClient;
  private MobileClient[] mobileClients;
  
  //constructor
  Mobile2Socket(PApplet parent) {
    socketClient = new Client(parent, host, port);
    mobileClients = new MobileClient[0];
  }
  
  //
  MobileClient update() { 
    
    MobileClient returnClient = null;
    
    if (socketClient.available() > 0) { 
      
      dataIn        = socketClient.readString();
      if(dataIn.indexOf("\0") >= 0) dataIn = dataIn.substring(0, dataIn.indexOf("\0"));
     
      clientAddress = split(dataIn, ",")[0];
      clientCommand = split(dataIn, ",")[1];
      
      if(DEBUG) {
        println("dataIn:" + dataIn);
        println("clientAddress:" + clientAddress);
        println("clientCommand:" + clientCommand);
      }
      
      if(clientCommand.equals("connect")) {
          
          MobileClient mClient  = new MobileClient();
          mClient.address       = clientAddress;
          mClient.command       = clientCommand;
          mClient.name          = split(dataIn, ",")[2];
          mClient.clientStatus  = "connected";
          mClient.action        = "";
              
          mobileClients = append(mobileClients, mClient);
          
          returnClient = mClient;

      } else if(clientCommand.equals("disconnect")) {
        
          //Search Client in Array
          MobileClient mClient = findMobileClient(mobileClients, clientAddress);
          
          //Delete Client in Array
          mobileClients = pop(mobileClients, mClient);
          
          returnClient = mClient;
          
      } else {
          
          MobileClient mClient = findMobileClient(mobileClients, clientAddress);
          mClient.lastCommand  = mClient.command;
          mClient.command      = clientCommand;
          mClient.clientStatus = "commanded";
          
          if(mClient.action.equals("") || mClient.action.equals("keyUp")) mClient.action = "keyDown";
          else mClient.action = "keyUp";
          
          returnClient = mClient;
        
      }
      
    }
    
    return returnClient; 
    
  }
  
}
